<?php

namespace app\home\model\user;

use basic\BaseModel;
use traits\ModelTrait;

/**
 * 会员的车辆管理
 * Class UserCar
 * @package app\home\model\user
 */
class UserCar extends BaseModel
{
    /**
     * 主键ID
     * @var string
     */
    protected $pk = "id";


    use ModelTrait;

    /**
     * 模型名称
     * @var string
     */
    protected $name = "user_car";

    /**
     * 获取所有的车辆
     * @param $param array 执行的条件
     * @return array
     */
    public static function getAllCar($param)
    {
        $model = self::setWhere($param);
        $count = $model->where("c.wxapp_id", self::$wxapp_id)
            ->where("c.is_del", 0)
            ->field("c.*, u.nickname, u.account")
            ->order("c.recent_time DESC, c.id DESC")->count();
        $data =  $model->where("c.wxapp_id", self::$wxapp_id)
            ->field("c.*, u.nickname, u.phone, wx.headimgurl")
            ->where("c.is_del", 0)
            ->order("c.recent_time DESC, c.id DESC")
            ->page((int)$param['page'], (int)$param['limit'])
            ->select()->each(function ($item, $key){
                $item["recent_time"] = date("Y-m-d H:i:s");
            });
        return compact("count", "data");
    }

    /**
     * 设置where条件
     * @param $param
     * @return UserCar
     */
    private static function setWhere($param)
    {
        $model = new self();
        $model = $model
            ->alias("c")
            ->join("user u", "u.uid = c.user_id")
            ->join("wechat_user wx", "wx.uid = c.user_id");
        if (isset($param["user_id"]) && !empty($param["user_id"])) $model = $model->where("c.user_id", "=", $param["user_id"]);
        if (isset($param["nickname"]) && !empty($param["user_id"])) $model = $model->where("u.nickname", "like", "%{$param['user_name']}%");
        if (isset($param["license_no"]) && !empty($param["license_no"])) $model = $model->where("c.license_no", "=", "%{$param['license_no']}%");
        if ($param['user_time_type'] == 'visitno' && $param['recent_time'] != '') {
            list($startTime, $endTime) = explode(' - ', $param['recent_time']);
            $endTime = strtotime($endTime) + 24 * 3600;
            $model = $model->where("c.recent_time < " . strtotime($startTime) . " OR c.recent_time > " . $endTime);
        }
        return $model;
    }


}